﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StoredProcedureExecutor.cs" company="DHGMS Solutions">
//   Copyright 2004-2014 DHGMS Solutions.
//      
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//      
//   http://www.apache.org/licenses/LICENSE-2.0
//      
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
// <summary>
//   Defines the StoredProcedureExecutor type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dhgms.TplHelper.Model.NoResultExecutor
{
    using System.Data.Common;

    public abstract class StoredProcedureExecutor<TDatabaseHelperClass, TParameterClass, TParameterCollection> : INoResultExecutor
        where TDatabaseHelperClass : Dhgms.DataManager.Model.Helper.Database.DatabaseHelperBase<TParameterClass, TParameterCollection>, new()
        where TParameterClass : DbParameter
        where TParameterCollection : DbParameterCollection
    {
        private readonly string connectionString;

        protected StoredProcedureExecutor(string connectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException("connectionString");
            }

            this.connectionString = connectionString;
        }

        /// <summary>Gets the SQL parameters.</summary>
        public abstract TParameterClass[] SqlParameters { get; }

        /// <summary>Gets the SQL stored procedure name.</summary>
        public abstract string ProcedureName { get; }

        /// <summary>Gets a value indicating whether to assume the SQL is safe.</summary>
        public virtual bool AssumeSqlSafe
        {
            get
            {
                return false;
            }
        }

        public System.Threading.Tasks.Task GetTask()
        {
            return TaskEx.Run(() => OnExecute());
        }

        private void OnExecute()
        {
            new TDatabaseHelperClass().ExecuteNonQueryStoredProcedure(this.connectionString, this.ProcedureName, this.SqlParameters, this.AssumeSqlSafe);
        }
    }
}
